﻿using System;
using System.Collections.Generic;
using SocialFilter.model;

namespace SocialFilter.controller
{
	// Filter out items based on filter words
	class FilterController
	{
		private List<Filter> filters;
		
		public FilterController()
		{
			filters = new List<Filter>();
		}
		
		public FilterController( string _filtersString )
		{
			filters = new List<Filter>();
			SetFilters( _filtersString );
		}
		
		public void SetFilters( string _filtersString )
		{
			filters.Clear();
			AddFilters( _filtersString );
		}
		
		public void SetFilters( List<Filter> _filters )
		{
			filters.Clear();
			AddFilters( _filters );
		}
		
		public void AddFilters( string _filtersString )
		{
			ParseFilters( _filtersString );
		}

		public void AddFilters( List<Filter> _filters )
		{
			filters.AddRange(_filters);
		}
		
		private void ParseFilters( string _filtersString )
		{
			// parse filters
			string[] filterStrings = _filtersString.Split( new char[]{','} );
			for ( int i = 0; i < filterStrings.Length; ++i )
			{
				if ( filterStrings[i].Trim() == "" )
				{
					continue;
				}
				filters.Add( new Filter(filterStrings[i]) );
			}
		}
		
		/**	Removes items that don't pass filters from list _items
		 * @param		_item	List of items to be filtered, will be modified
		 */
		public void FilterItems( List<FeedItem> _items )
		{
			for ( int i = 0; i < _items.Count; ++i )
			{
				if ( !FilterItem( _items[i] ) )
				{
					_items.RemoveAt(i);
					--i;
				}
			}
		}
		
		public bool FilterItem( FeedItem _item )
		{
			for ( int i = 0; i < filters.Count; ++i )
			{
				if ( filters[i].FilterItem(_item) == false )
				{
					return false;
				}
			}
			return true;
		}
	}
}
